package com.shanlitech.bluetooth;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.shanlitech.lbs.map.LbsDatabase;
import com.shanlitech.lbs.utils.LogUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;

public class MapBuilder {
    private static final String FILE_NAME = "map_sz.json";

    private final Context mContext;

    public MapBuilder(Context context) {
        mContext = context;
    }

    public LbsDatabase build() {
        if( LbsDatabase.getInstance() != null ) {
            return LbsDatabase.getInstance();
        }

        try {
            InputStream in = null;
            File file = new File(mContext.getFilesDir().getAbsolutePath(), FILE_NAME);
            if (file.canRead()) {
                in = new FileInputStream(file);
            } else {
                AssetManager assetManager = mContext.getAssets();
                in = assetManager.open(FILE_NAME);
            }
            if (in != null) {
                JSONObject json = loadJson(in);
                if (json != null) {
                    return LbsDatabase.create(json);
                }
            }
        } catch( ParseException | IOException | JSONException ex ) {
            LogUtils.log(ex.getMessage());
        }
        return null;
    }

    private JSONObject loadJson(InputStream in) {
        try {
            final StringBuilder sb = new StringBuilder();
            try(BufferedReader br = new BufferedReader(new InputStreamReader(in)) ) {
                for(String line; (line = br.readLine()) != null; ) {
                    sb.append(line).append("\n");
                }
            }
            return JSONObject.parseObject(sb.toString());
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void writeFile(Context context) {
        if( LbsDatabase.getInstance() == null ) {
            return;
        }
        File file = new File(context.getFilesDir().getAbsolutePath(),FILE_NAME);
        try {
            LbsDatabase.getInstance().writeFile(new FileOutputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
